<?php

include_once('../../index.php');
include_once('templates/core/Smarty.class.php');
include_once('logo.php');

$isReceiveForm = count($_POST) > 0;
$isIdentify = false;
$message = '';

if ($isReceiveForm) {
  $isReceiveData =
    isset($_POST['identify'],
          $_POST['hash']);

  if (!$isReceiveData) {
    $message = 'Ingrese sus datos';
  }
}

//The user send correctly indentify and hash
if ($isReceiveForm &&
    $isReceiveData) {
  //index properties
  $post = new Post($db);
  $post->identify = $_POST['identify'];
  $post->hash = hash('sha512', $_POST['hash']);
  $isIdentify = $post->identify();
}

//Is identify user
if ($isIdentify) {
  // expire in a year
  setcookie('identify', $_POST['identify'], time()+29808000, "/");
  setcookie('hash', hash('sha512', $_POST['hash']), time()+29808000, "/");
}

// WELCOME
if ($isIdentify &&
    !$isReceiveForm) {
  $message = 'Bienvenido';
}

// RETYPE YOUR DATA
if (!$isIdentify && $isReceiveForm) {
  $message = 'Reingrese sus datos correctamente';
}

//Is not identify user
if (!$isIdentify) {
  //DECLARE FORM VARIABLES
  $smarty->assign('identify', '');
  $smarty->assign('hash', '');
  $smarty->assign('message', $message);

  $page = isset($_GET['page']) ? $_GET['page'] : 'login';

  $smarty->display("templates/{$page}.tpl");
  return;
}

//SUPERUSER PROCESS
$isSuperUser = $post->is_super_user();

//is_super_user process
if ($isSuperUser) {
  header('Location: users.php?page=read');
}

$isLibreTubeUser = !$isSuperUser;

if ($isLibreTubeUser) {
  // Go to exclusive videoteca area
  header('Location: /');
}

?>
